﻿using System;
using System.Reflection;
using System.Configuration;
using Travianer.Common;
namespace Travianer.Factory
{
    /// <summary>
    /// Abstract Factory pattern to create the DAL。
    /// 如果在这里创建对象报错，请检查web.config里是否修改了<add key="DAL" value="Maticsoft.SQLServerDAL" />。
    /// </summary>
    public sealed class DataAccess
    {
        private static readonly string AssemblyPath = Configuration.AssemblyPath;
        private static readonly string AssemblyPathPrefix = Configuration.AssemblyPathPrefix;
        public DataAccess()
        { }

        #region CreateObject

        //不使用缓存
        private static object CreateObject(string AssemblyPath, string classNamespace)
        {
            try
            {
                object objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                return objType;
            }
            catch//(System.Exception ex)
            {
                //string str=ex.Message;// 记录错误日志
                return null;
            }

        }
        #endregion

        #region 泛型生成
        ///// <summary>
        ///// 创建数据层接口。
        ///// </summary>
        //public static t Create(string ClassName)
        //{

        //    string ClassNamespace = AssemblyPath +"."+ ClassName;
        //    object objType = CreateObject(AssemblyPath, ClassNamespace);
        //    return (t)objType;
        //}
        #endregion

        #region CreateSysManage
        //public static Travianer.IDAL.ISysManage CreateSysManage()
        //{
        //    //方式1			
        //    //return (Travianer.IDAL.ISysManage)Assembly.Load(AssemblyPath).CreateInstance(AssemblyPath+".SysManage");

        //    //方式2 			
        //    string classNamespace = AssemblyPath + ".SysManage";
        //    object objType = CreateObject(AssemblyPath, classNamespace);
        //    return (Travianer.IDAL.ISysManage)objType;
        //}
        #endregion



        /// <summary>
        /// 创建AutoResService数据层接口。
        /// </summary>
        public static Travianer.IService.IAutoResService CreateAutoResService()
        {

            string ClassNamespace = AssemblyPathPrefix + AssemblyPath + ".AutoResService";
            object objType = CreateObject(AssemblyPath, ClassNamespace);
            return (Travianer.IService.IAutoResService)objType;
        }
        /// <summary>
        /// 创建IAutoBuildService数据层接口。
        /// </summary>
        public static Travianer.IService.IAutoBuildService CreateAutoBuildService()
        {

            string ClassNamespace = AssemblyPathPrefix + AssemblyPath + ".AutoBuildService";
            object objType = CreateObject(AssemblyPath, ClassNamespace);
            return (Travianer.IService.IAutoBuildService)objType;
        }

    }
}